<?php session_start();?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>修改密码</title>
</head>
<body>
    <?php
    // 包含数据库连接文件
    include '../db.php';

    // 检查是否有提交表单
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // 获取表单数据
        $user = $_SESSION['username'];
        $oldpwd = $_POST['oldpwd'];
        $pass1 = $_POST['pass1'];
        $pass2 = $_POST['pass2'];

        // 检查旧密码是否正确
        $sql = "SELECT * FROM usertable WHERE username = '$user' AND password = '$oldpwd'";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            // 旧密码正确，检查新密码是否与确认密码一致
            if ($pass1 === $pass2) {
                // 更新密码
                $updateSql = "UPDATE usertable SET password = '$pass1' WHERE username = '$user'";
                if ($conn->query($updateSql) === TRUE) {
                    echo "
                        <script>
                            alert('密码修改成功！');
                            window.location.href = '../User/login.html'; // 跳转到登录页面
                        </script>
                    "; 
                }
                else {
                    echo "
                        <script>
                            alert('密码修改失败：" . $conn->error . "');
                            window.location.href = 'modifypwd1.php'; // 跳转到修改密码页面
                        </script>
                    ";
                }
            }  
        }
        else {
            echo "
                <script>
                    alert('旧密码错误！');
                    window.location.href = 'modifypwd1.php'; // 跳转到修改密码页面
                </script>
            "; 
        }
    }
    else {
        echo "
            <script>
                alert('请先登录！');
                window.location.href = '../User/login1.php'; // 跳转到登录页面
            </script>
        "; 
    }
    // 关闭数据库连接
    $conn->close();
    ?>
    <?php include '../footer.php'; ?>
</body>
</html>